﻿using System;
using System.IO;
using Microsoft.Office.Server.Diagnostics;
using Microsoft.SharePoint;

namespace WoltersKluwer.SPChainGang.Core.Util
{
    public static class Logger
    {
        public static string LOG_FILE_NAME = "SPChainGang.log";
        //TODO: implement own TraceProvider
        public static void Log(Guid jobId, string message, params object[] data)
        {
            var messageToLog = String.Format(Constants.GlobalConstants.LogEntryTemplate, DateTime.Now, jobId, message);
            SPSecurity.RunWithElevatedPrivileges(
                () => PortalLog.LogString(messageToLog, data));
            LogToFile(messageToLog, data);
        }

        public static void LogError(Guid jobId, string message, Exception e)
        {
            var messageToLog = String.Format(Constants.GlobalConstants.LogExceptionTemplate, DateTime.Now, jobId, message, e);
            SPSecurity.RunWithElevatedPrivileges(
                () => PortalLog.LogString(messageToLog));
            LogToFile(messageToLog);
        }

        private static void LogToFile(string message, params object[] parameters) //TODO: remove this and make a proper log (could be stored in the reports library as well)
        {
            string tempPath = Path.GetTempPath();
            string logFileName = string.Concat(tempPath, LOG_FILE_NAME);
            using (var file = File.AppendText(logFileName))
            {                
                file.WriteLine(String.Format(message, parameters));
                file.WriteLine();
            }            
        }
    }
}
